<?php

namespace Home\Model;

use Think\Model;

class MemberModel extends Model {

    /**
     * 注册用户
     */
    public function register($phone, $username, $password, $nickname='') {
        //$data['email'] = $email;
        $data['phone'] = $phone;
        $data['nickname'] = $nickname;
        $data['username'] = rand_username();
        $data['password'] = strongmd5($password);
        $data['point'] = 0;
        $data['experience'] = 0;
        $data['money'] = 0;
        $data['level_id'] = 1;
        $data['is_valid_phone'] = 0;
        $data['is_valid_email'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        $data['ex_invitation'] = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 6);


        $member_id = $this->add($data);
        if ($member_id > 0) {
            //增加会员信息表记录
            $MemberInfoObj = new \Home\Model\MemberInfoModel();
            $MemberInfoObj->member_id = $member_id;
            $MemberInfoObj->create_ip = get_client_ip();
            $MemberInfoObj->add();
            //注册赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_register($member_id, $config['point_register']);
        }
        return $member_id;
    }
    
     /*
     * 第三方登录注册用户
     */
    public function register_auto($data_field,$nickname,$openid) {
        if($this->exist_nickname($nickname,'') > 0) {
            $nickname .=  rand(0, 99);
            if($this->exist_nickname($nickname,'') > 0) {
                $nickname .=  rand(0, 99);
            }
        }
        $data['email'] = '';
        $data['phone'] = '';
        $data['nickname'] = $nickname;
        $data['username'] = '';
        $data['password'] = '';
        $data['point'] = 0;
        $data['experience'] = 0;
        $data['money'] = 0;
        $data['level_id'] = 1;
        $data['is_valid_phone'] = 0;
        $data['is_valid_email'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        $data[$data_field] = $openid;
        $member_id = $this->add($data);
        if ($member_id > 0) {
            //增加会员信息表记录
            $MemberInfoObj = new \Home\Model\MemberInfoModel();
            $MemberInfoObj->member_id = $member_id;
            $MemberInfoObj->create_ip = get_client_ip();
            $MemberInfoObj->add();
            //注册赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_register($member_id, $config['point_register']);
        }
        return $member_id;
    }

    /**
    *用户登陆操作 
    * @param string $username 用户名
    * @param type $password 密码
    * @param type $remember 是否记住密码
    * @return int 1：登陆成功，-1：找不到用户  -2：用户已禁用 -3：用户名或密码不能为空
    */
    public function login($username, $password, $remember = 0) {
        if (trim($username) == '' || trim($password) == '') {
            return -3;
        }
        $password = strongmd5($password);
        $arr = $this->field('member_id,status')->where(Array('phone' => $username, 'password' => $password))->find();
        if (is_array($arr)) {
            if ($arr['status'] != 1) {
                return -2;
            }
			
			
            session('member_id', $arr['member_id']);
            $key_login_code = $arr['member_id'] . randomname(30);
            $arr['code_keep_login'] = $key_login_code;
            $this->save($arr);
            if ($remember == 1) {
                $expire = 604800;
                cookie('member_id', $arr['member_id'], $expire);
                cookie('member_keep_login', $key_login_code, $expire);
            }
            //登录信息
            $LoginObj = new \Home\Model\MemberLoginModel();
            $LoginObj->add_login_record($arr['member_id']);
            //登陆赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_login($arr['member_id'], $config['point_login_day']);
            return 1;
        }
        return -1;
    }
	
	   	/*
     * 第三方登陆用户
     */
    public function login_api($login_bind_name, $login_bind_type=1, $remember=0) {
		
        if (trim($login_bind_name) == '' || trim($login_bind_type) == '') {
            return -3;
        }
        switch($login_bind_type){
		case 1:$map['login_weixin']=$login_bind_name;break;
		case 2:$map['login_weibo']=$login_bind_name;break;
		}
	
        $arr = $this->field('member_id,phone,nickname,status')->where($map)->find();
		 // echo $this->_sql();
	    if(empty($arr)){//正式表没有就调用临时表
		$arr = M('member_temp')->field('member_id,phone,nickname,status')->where($map)->find();
		//echo $this->_sql();
		}
	     session('nickname', $arr['nickname']);//昵称
	
        if (is_array($arr)) {
            if ($arr['status'] == 2 || $arr['status'] == 3) {
                return -2;//被封或删除无法登录
            }elseif($arr['phone']==''){//手机为空的情况
			
			  return 2;//还未绑定
			}else{
			/*
			session('member_id', $arr['member_id']);
            $key_login_code = $arr['member_id'] . randomname(30);                  
            $arr['code_keep_login'] = $key_login_code;  
			$arr['login_ip'] = get_client_ip(); 
            $arr['last_login_time'] = time();  
			
            $this->save($arr);
			*/
			session('member_id', $arr['member_id']);
            $key_login_code = $arr['member_id'] . randomname(30);
            $arr['code_keep_login'] = $key_login_code;
            $this->save($arr);
            if ($remember == 1) {
                $expire = 604800;
                cookie('member_id', $arr['member_id'], $expire);
                cookie('member_keep_login', $key_login_code, $expire);
            }
            //登录信息
            $LoginObj = new \Home\Model\MemberLoginModel();
            $LoginObj->add_login_record($arr['member_id']);
            //登陆赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_login($arr['member_id'], $config['point_login_day']);
			 return 1;//登录成功
			}
          
          
        }
        return -1;
    }
	
	
	
    
    /**
     * 会员登出
     * @return string
     */
    public function logout() {
        cookie('member_id', null);
        cookie('member_keep_login', null);
        cookie(null);
        session('member_id', null);
        session(null);
        return '1';
    }
    
    /**
     * 检测旧密码是否正常
     * @param int $member_id  会员ID
     * @param string $old_password 加密后的密码
     * @return boolean true：表示正确；false：表示错误
     */
    public function check_old_password($member_id,$old_password) {
        $data_password = $this->getFieldByMemberId($member_id, 'password');
        if ($old_password != $data_password) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * 修改密码
     * @param int $member_id 会员ID
     * @param string $new_password 新密码
     * @param boolean $is_md5 是否是加密后的密码
     * @return int 1：修改成功；0：修改失败
     */
    public function change_password($member_id,$new_password,$is_md5 = true) {
       if(!$is_md5) {
           $new_password = strongmd5($new_password);
       }
       return $this->where(array('member_id'=>$member_id))->setField('password', $new_password);
    }
    
     /**
     * 修改邮箱
     * @param int $member_id 会员ID
     * @param string $new_email 新邮箱
     * @return int 1：修改成功；0：修改失败
     */
    public function change_email($member_id,$new_email) {
       $data['member_id'] = $member_id;
       $data['email'] = $new_email;
       $data['is_valid_email'] = 0;
       return $this->save($data);
    }
    
     /**
     * 修改手机
     * @param int $member_id 会员ID
     * @param string $new_phone 新手机
     * @return int 1：修改成功；0：修改失败
     */
    public function change_phone($member_id,$new_phone) {
       $data['member_id'] = $member_id;
       $data['phone'] = $new_phone;
       $data['is_valid_phone'] = 0;
       return $this->save($data);
    }

    /**
     * 更新用户登陆状态
     */
    public function update_state() {
        $member_id = I('session.member_id', 0);
        if ($member_id == 0) {
            $cookie_member_id = I('cookie.member_id', 0);
            $cookie_key_login_code = I('cookie.member_keep_login', '');
            if ($cookie_member_id > 0 && $cookie_key_login_code != '') {
                $arr = $this->field('member_id')->where(Array('member_id' => $cookie_member_id, 'code_keep_login' => $cookie_key_login_code, 'status'=>1))->find();
                if (!empty($arr)) {
                    session('member_id', $arr['member_id']);
                    //登陆赠送积分
                    $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
                    $config = S('config');
                    $MemberPointObj->add_by_login($member_id, $config['point_login_day']);
                }
            }
        }
    }

    /**
     * 判断用户名是否存在，存在返回1
     * @param string $nickname 用户名
     * @param int $member_id 排除用户ID
     */
    public function exist_username($username, $member_id) {
        return $this->where(array('username' => $username, 'member_id' => array('neq', $member_id)))->count();
    }
    
    /**
     * 判断昵称是否存在，存在返回1
     * @param string $nickname 用户名
     * @param int $member_id 排除用户ID
     */
    public function exist_nickname($nickname, $member_id) {
        return $this->where(array('nickname' => $nickname, 'member_id' => array('neq', $member_id)))->count();
    }

    /**
     * 判断邮箱是否存在，存在返回1
     * @param string $email 邮箱
     * @param int $member_id 排除用户ID
     */
    public function exist_email($email, $member_id) {
        return $this->where(array('email' => $email, 'member_id' => array('neq', $member_id)))->count();
    }
    
    /**
     * 判断手机是否存在，存在返回1
     * @param string $phone 昵称
     * @param int $member_id 排除用户ID
     */
    public function exist_phone($phone, $member_id) {
        return $this->where(array('phone' => $phone, 'member_id' => array('neq', $member_id)))->count();
    }
    
    /**
     * 获得会员邮箱账号
     * @param int $member_id 会员ID
     * @return string 会员邮箱账号
     */
    public function get_email($member_id) {
        return $this->where(array('member_id'=>$member_id))->getField('email');
    }
    
    /**
     * 获得会员手机账号
     * @param int $member_id 会员ID
     * @return string 会员手机号码
     */
    public function get_phone($member_id) {
        return $this->where(array('member_id'=>$member_id))->getField('phone');
    }
    
    /**
     * 获得会员头像
     * @param int $member_id 会员ID
     * @return string 会员头像地址
     */
    public function get_headpic($member_id) {
        $headpic = $this->getFieldByMemberId($member_id,'headpic');
        if(empty($headpic)) {
            $headpic = '/Public/home/images/header.jpg';
        }
        return $headpic;
    }
    
    /**
     * 获取会员显示名称
     */
    public function show_member_name($member_id) {
		
		$row = $this->field('username,phone,nickname')->where(array('member_id'=>$member_id))->find();
        if(!empty($row)) {
            if (!empty($row['nickname'])) { 
                return $row['nickname'];
            }elseif (!empty($row['phone'])) {
                return  substr_replace($row['phone'],'****',3,4);
            } else {
                return $member_id;
            }
        } else {
            return '无此用户';
        }
		

    }
	
	
	
	 /**
     * 获取会员等级
     */
    public function show_member_level($member_id) {
		
		$level_id = $this->where(array('member_id'=>$member_id))->getField('level_id');
        if($level_id>0) {
           return $level_id;
        } else {
            return '0';
        }
		

    }
    
     /**
     * 获取会员头像
     */
    public function show_headpic($member_id, $size = 80) {
        $headpic = $this->getFieldByMemberId($member_id,'headpic');
        if($size !== 80) {
            $headpic = str_replace($headpic, 'headpic/80', 'headpic/'.$size);
        }
        return $headpic;
    }
    
    /**
     * 获取会员金币
     * @param int $member_id 会员ID
     * @return int 金币
     */
    public function get_point($member_id) {
        return $this->getFieldByMemberId($member_id,'point');
    }
   
    
    /**
     * 获取会员余额
     * @param int $member_id 会员ID
     * @return int 金币
     */
    public function get_money($member_id) {
        return $this->getFieldByMemberId($member_id,'money');
    }
    
    /**
     * 更新会员等级
     * @param type $member_id
     */
    public function update_level($member_id) {
        $experience = $this->get_experience($member_id);
        $MemberLevel = new \Home\Model\MemberLevelModel();
        $member_level = $MemberLevel->get_level($experience);
        return $this->where('member_id='.$member_id)->setField('level_id',$member_level); 
    }
    
        /**
     * 更新会员等级
     * @param type $member_id
     */
    public function update_level_all() {
        $member = $this->field('member_id')->select();
        print($member);
        $count = 0;
        foreach($member as $m) {
            $count += $this->update_level($m['member_id']);
        }
        echo $count;
    }
	
		   	    /**
     * 会员重置密码
     * @param type $param
     */
    public function reset_password($username, $newpassword) {
        $data['password'] = strongmd5($newpassword);
        $flag = $this->where(Array('phone'=>$username))->save($data);
        return $flag;
    }

}
